import { defineStore, storeToRefs } from 'pinia'
import { canvas } from './canvasInstance'
import { useCanvasParameterStore } from './canvasParameter'
import { Node } from '@antv/x6'
import { getCenter, smoothCenterTo } from './otherFun'

export const useCanvasSearchStore = defineStore('canvasSearch', {
  state: () => ({
    //搜索栏显示隐藏
    isSearchBoxShow: false,
    //搜索框内容
    searchContent: '',
    //是否全字匹配
    isMatchAll: false,
    //当前搜索结果索引
    currentSearchIndex: 0,
    //搜索结果
    searchResult: [] as string[]
  }),

  actions: {
    //切换搜索栏状态
    switchSearchBox() {
      this.isSearchBoxShow = !this.isSearchBoxShow
    },

    //搜索内容
    searchContentChange() {
      this.searchResult = []
      const canvas = window.api.handleCanvasData('getCanvas', 'canvas2D', false, [])
      const nodes = canvas.nodes

      nodes.forEach((node) => {
        if (node.id.includes(this.searchContent)) {
          this.searchResult.push(node.id)
          return
        }
        if (this.isMatchAll) {
          if (node.name === this.searchContent) {
            this.searchResult.push(node.id)
            return
          }
        } else {
          if (node.name.includes(this.searchContent)) {
            this.searchResult.push(node.id)
          }
        }
      })

      this.changeSearchIndex('next')
    },

    //搜索结果索引变化
    changeSearchIndex(mark: 'prev' | 'next') {
      if (this.searchResult.length === 0) {
        this.currentSearchIndex = 0
        return
      }

      if (mark === 'prev') {
        if (this.currentSearchIndex === 0) {
          this.currentSearchIndex = this.searchResult.length - 1
        } else {
          this.currentSearchIndex--
        }
      }
      if (mark === 'next') {
        if (this.currentSearchIndex >= this.searchResult.length - 1) {
          this.currentSearchIndex = 0
        } else {
          this.currentSearchIndex++
        }
      }

      const id = this.searchResult[this.currentSearchIndex]
      const node = canvas.getCellById(id) as Node
      const { x, y } = node.getPosition()
      const { x: sX, y: sY } = getCenter()
      smoothCenterTo(sX, sY, x, y)
      const { selectedNode } = storeToRefs(useCanvasParameterStore())
      selectedNode.value = node
    }
  }
})
